﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using DBAccessLibrary;
using DBAccessLibrary.Model;
using DevExpress.Xpf.Editors;
using Microsoft.Win32;
using QueryResource.Common;
using QueryResource.ViewModel;

namespace DevControlLibrary.UI
{
    /// <summary>
    /// DbConnectionControl.xaml 的交互逻辑
    /// </summary>
    public partial class DbConnectionControl : UserControl
    {
        readonly RegistDBViewModel _viewModel;
        private readonly Dictionary<string, string> _odbcDic = new Dictionary<string, string>();
        private string _selectTabHearder;
        public DbConnectionControl()
        {
            _viewModel = new RegistDBViewModel();
            this.DataContext = _viewModel;
            InitializeComponent();

            SubmitAction = Submit;
        }
        //结果委托
        public Func<RegistDBViewModel> SubmitAction { get; private set; }

      public void SetData(ConnectionModel model)
      {
          _viewModel.DataSource.ConnectType = model.ConnectType;
          _viewModel.DataSource.Server = model.Server;
          _viewModel.DataSource.DataBase = model.DataBase;
          _viewModel.DataSource.UserID = model.UserID;
          _viewModel.DataSource.PassWord = model.PassWord;
          _viewModel.DataSource.ConnectionStr = model.ConnectionStr;
      }

        private void ButtonExcelFileClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog
            {
                ValidateNames = true,
                CheckPathExists = true,
                CheckFileExists = true,
                Filter = "excel 2003 （*.xls)|*.xls|excel 2007/2010 (*.xlsx)|*.xlsx"
            };
            bool? showDialog = dlg.ShowDialog();
            if (showDialog != null && showDialog.Value)
            {
                _viewModel.DataSource.DataBase =dlg.SafeFileName;
                _viewModel.DataSource.Server = System.IO.Path.GetDirectoryName(dlg.FileName);
                switch(System.IO.Path.GetExtension(dlg.FileName))
                {
                    case ".xls":
                        _viewModel.DataSource.ConnectionStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dlg.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                        break;
                    case ".xlsx":
                        _viewModel.DataSource.ConnectionStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dlg.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                        break;
                }
            }
        }


        private RegistDBViewModel Submit()
        {
            switch(_selectTabHearder)
            {
                case "常用连接":
                    {
                        if (_viewModel.DataSource.DataBase == null ||
                           _viewModel.DataSource.UserID == null ||
                           _viewModel.DataSource.Server == null)
                        {
                            MessageBoxHelper.Show("数据库基本数据不完全，请查看");
                            return null;
                        }
                    }
                    break;
                case "Excel":
                    {
                        if (string.IsNullOrEmpty(_viewModel.DataSource.DataBase) ||
                                string.IsNullOrEmpty(_viewModel.DataSource.ConnectionStr))
                        {
                            MessageBoxHelper.Show("数据库基本数据不完全，请查看");
                            return null ;
                        }
                        _viewModel.DataSource.ConnectType = DBAccessLibrary.Model.DBType.Ole;
                    }
                    break;
                case "ODBC":
                    {
                        if (string.IsNullOrEmpty(_viewModel.DataSource.DataBase) ||
                                string.IsNullOrEmpty(_viewModel.DataSource.ConnectionStr))
                        {
                            MessageBoxHelper.Show("数据库基本数据不完全，请查看");
                            return null;
                        }
                        _viewModel.DataSource.ConnectType = DBAccessLibrary.Model.DBType.ODBC;
                    }
                    break;
                default:
                    return null;
            }
            return _viewModel;
        }

        private void LayoutGroup_SelectedTabChildChanged(object sender, DevExpress.Xpf.Core.ValueChangedEventArgs<FrameworkElement> e)
        {
            DevExpress.Xpf.LayoutControl.LayoutGroup group = e.NewValue as DevExpress.Xpf.LayoutControl.LayoutGroup;
            if (group == null)
                return;
            _selectTabHearder = group.Header.ToString();
           
            if (_selectTabHearder == "ODBC")
            {
                if (this.CbOdbcType.ItemsSource == null)
                {
                    try
                    {
                        this.CbOdbcType.ItemsSource = GetOdbcNames();
                    }
                    catch(Exception ex)
                    {
                        MessageBoxHelper.Show(ex.Message);
                    }
                }
            }
        }

        private IEnumerable<string> GetOdbcNames()
        {
            List<string> list = new List<string>();
            RegistryKey root = Registry.CurrentUser;
            RegistryKey openSubKey = root.OpenSubKey("SoftWare");
            if (openSubKey != null)
            {
                RegistryKey registryKey = openSubKey.OpenSubKey("ODBC");
                if (registryKey != null)
                {
                    RegistryKey odbc = registryKey.OpenSubKey("ODBC.INI");

                    if (odbc != null)
                    {
                        RegistryKey source = odbc.OpenSubKey("ODBC Data Sources");
                        if (source != null)
                        {
                            foreach (string key in source.GetValueNames())
                            {
                                _odbcDic.Add(key,source.GetValue(key).ToString());
                            }
                            list.AddRange(source.GetValueNames());
                        }
                    }
                }
            }

            root = Registry.LocalMachine;
            openSubKey = root.OpenSubKey("SoftWare");
            if (openSubKey != null)
            {
                 RegistryKey registryKey = openSubKey.OpenSubKey("ODBC");
                 if (registryKey != null)
                 {
                     RegistryKey odbc = registryKey.OpenSubKey("ODBC.INI");
                      if (odbc != null)
            {
                RegistryKey source = odbc.OpenSubKey("ODBC Data Sources");
                if (source != null)
                {
                    foreach (string key in source.GetValueNames())
                    {
                        _odbcDic.Add(key, source.GetValue(key).ToString());
                    }
                    list.AddRange(source.GetValueNames());
                }
            }
                 }
            }
           
            return list;
        }

        private void CbOdbcType_SelectedIndexChanged(object sender, RoutedEventArgs e)
        {
            if(CbOdbcType.Text != string.Empty)
            {
                _viewModel.DataSource.Server = _odbcDic[CbOdbcType.Text];
                _viewModel.DataSource.ConnectionStr = string.Format("Dsn={0};Uid={1};Pwd={2}",
                    CbOdbcType.Text,
                    _viewModel.DataSource.UserID,
                    _viewModel.DataSource.PassWord);
            }
        }

        private void OdbcEditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            _viewModel.DataSource.ConnectionStr = string.Format("Dsn={0};Uid={1};Pwd={2}",
                   CbOdbcType.Text,
                   _viewModel.DataSource.UserID,
                   _viewModel.DataSource.PassWord);
        }

        #region 数据库为选择项


        
        private List<ConnectionModel> _connectList;
        public void CreateCombox()
        {
            _connectList = new List<ConnectionModel>();

            ComboBoxEdit com = new ComboBoxEdit
                                   {
                                       AutoComplete = true,
                                       Height=23,
                                       Width=195,
                                       HorizontalAlignment= System.Windows.HorizontalAlignment.Left,
                                       VerticalAlignment = System.Windows.VerticalAlignment.Top
                                   };
            Binding bind = new Binding
                               {
                                   Source = this.DataContext, 
                                   Path = new PropertyPath("DataSource.DataBase")
                               };
            com.SetBinding(TextBlock.TextProperty, bind);
            com.SelectedIndexChanged += (sender, e) => SetConnectionModel(_viewModel.DataSource, com.Text);

            try
            {
                foreach (DataBaseEntity entity in SysCache.ServerList)
                {
                    foreach (DBEntity db in entity.ChildNodes)
                    {
                        _connectList.Add(db.ConnectionSource);
                        com.Items.Add(db.ConnectionSource.DataBase);
                    }
                }
            }
            catch
            {
                MessageBoxHelper.Show("有数据库正在连接，无法显示已连接的信息");
            }

            this.TbdbName.Content = com;
        }
        private void SetConnectionModel(ConnectionModel connection, string database)
        {
            ConnectionModel serverConnection = null;
            if (!string.IsNullOrEmpty(connection.Server))
            {
                serverConnection = _connectList.FirstOrDefault(o => o.Server == connection.Server && o.DataBase == database);
            }
            if (serverConnection == null)
            {
                serverConnection = _connectList.FirstOrDefault(o => o.DataBase == database);
            }
            if (serverConnection != null)
            {
                connection.ConnectType = serverConnection.ConnectType;
                connection.DataBase = serverConnection.DataBase;
                connection.PassWord = serverConnection.PassWord;
                connection.Server = serverConnection.Server;
                connection.UserID = serverConnection.UserID;
                connection.ConnectionStr = serverConnection.ConnectionStr;
            }
        }
        #endregion
    }
}
